{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义HMM模型的参数\n",
    "\n",
    "# 隐含状态数量\n",
    "num_states = 3\n",
    "\n",
    "# 观测状态数量\n",
    "num_observations = 2\n",
    "\n",
    "# 初始状态概率向量（初始时每个隐含状态的概率）\n",
    "initial_probabilities = np.array([0.6, 0.3, 0.1])\n",
    "\n",
    "# 转移概率矩阵（从一个隐含状态到另一个隐含状态的概率）\n",
    "transition_matrix = np.array([[0.7, 0.2, 0.1],\n",
    "                              [0.3, 0.5, 0.2],\n",
    "                              [0.1, 0.4, 0.5]])\n",
    "\n",
    "# 发射概率矩阵（从每个隐含状态观察到每个观测状态的概率）\n",
    "emission_matrix = np.array([[0.1, 0.4],\n",
    "                            [0.3, 0.6],\n",
    "                            [0.7, 0.0]])\n",
    "\n",
    "# 观测序列\n",
    "observations = [0, 1, 0]\n",
    "\n",
    "# 初始化前向概率矩阵\n",
    "num_time_steps = len(observations)\n",
    "forward_probabilities = np.zeros((num_states, num_time_steps))\n",
    "\n",
    "# 初始化第一个时间步的前向概率\n",
    "forward_probabilities[:, 0] = initial_probabilities * \\\n",
    "    emission_matrix[:, observations[0]]\n",
    "\n",
    "# 递归计算前向概率\n",
    "for t in range(1, num_time_steps):\n",
    "    for s in range(num_states):\n",
    "        forward_probabilities[s, t] = np.sum(\n",
    "            forward_probabilities[:, t - 1] * transition_matrix[:, s]) * emission_matrix[s, observations[t]]\n",
    "\n",
    "# 最终前向概率\n",
    "final_forward_probabilities = forward_probabilities[:, -1]\n",
    "\n",
    "# 计算观测序列的概率（前向概率的总和）\n",
    "observed_probability = np.sum(final_forward_probabilities)\n",
    "\n",
    "print(\"观测序列的概率:\", observed_probability)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
